<template>
  <view class="page-body">
    <view class="page-section page-section-gap">
      <!-- 绑定点击事件到显示导航按钮 -->
      <button @click="showNavigation">导航到终点</button>
      <!-- 确保地图组件能够响应 latitude 和 longitude 属性的变化 -->
      <map 
        id="myMap" 
        style="width: 100%; height: 300px;" 
        :latitude="currentLocation.latitude" 
        :longitude="currentLocation.longitude" 
        :markers="mapMarkers"
      >
      </map>
      <view class="shops-list">
        <!-- 商店列表 -->
        <view v-for="(shop, index) in shops" :key="shop.storeId" class="shop-item">
          <!-- 使用 v-bind 来绑定 src 属性 -->
          <image class="shop-image" v-bind:src="shop.storeImgUrl" mode="aspectFill" style="border-radius: 15px;"/>
          <view class="shop-info">
            <text class="shop-name">{{shop.storeName}}</text>
            <text class="shop-address">{{shop.storeAddress}}</text>
          </view>
          <button @click="showNavigation(shop.storeLatitude, shop.storeLongitude)">导航</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script >
	import { store } from '@/uni_modules/uni-id-pages/common/store.js'
		import { get, post, removeToken } from '@/utils/api.js';
export default {
  data() {
    return {
	  shops: [], 
      id: 0,
      title: 'map',
      // 初始经纬度设置为北京，实际应用中应获取用户当前位置
      latitude: 39.909,
      longitude: 116.39742,
      covers: [
        // 终点坐标，这里设置一个静态坐标作为示例
        { latitude: 39.9087, longitude: 116.3973, iconPath: '/static/all.png' },
        // 其他坐标点...
      ],
      // 用户当前位置坐标
      currentLocation: {
        latitude: 0,
        longitude: 0,
      },
	  mapMarkers: [], // 用于存储地图上的标点
	  ky:"e7bf74027b900e1fa4345b4896c202eb",
	  amapPlugin: null,
    };
  },
  methods: {
    // 获取用户当前位置
        getCurrentLocation() {
          const that = this;
          uni.getLocation({
            type: 'wgs84',
            success: function (res) {
              that.currentLocation.latitude = res.latitude;
              that.currentLocation.longitude = res.longitude;
              // 刷新地图，使之中心移动到当前位置
              that.$forceUpdate(); // 确保地图组件响应数据变化
            },
          });
        },
		 fetchShopsData() {
				post('/store/displayStoreList',
				 {}
				 , {
				  needToken: true, 	
					success: (res) => {
					if (res.statusCode === 200) {
						 this.shops = res.data 
						this.addMarkersToMap(res.data); 
						}
					}
				}); 
		    },
			 addMarkersToMap(shops) {
			      const that = this;
			      this.mapMarkers = []; // 重置标点数组
			      shops.forEach((shop) => {
			        const marker = {
			          latitude: parseFloat(shop.latitude),
			          longitude: parseFloat(shop.longitude),
			          iconPath: '/static/111.png', // 标点图标路径
					  scale: 0.1,
			        };
			        this.mapMarkers.push(marker);
			      });
			},
    // 显示导航功能
    showNavigation(latitude, longitude) {
      // 确保参数不为空
      if (!latitude || !longitude) {
        console.error('纬度或经度为空，无法导航');
        return;
      }
    
      // 构建高德地图导航的 URL Scheme
      const urlScheme = `amapuri://route/plan/?sourceApplication=yourAppName&dlat=${encodeURIComponent(latitude)}&dlon=${encodeURIComponent(longitude)}&dev=0&t=0&style=0`;
    
      // 构建网页版高德地图导航 URL
      const webUrl = `http://uri.amap.com/navigation?to=${encodeURIComponent(latitude)},${encodeURIComponent(longitude)}`;
    
      // 检查是否为 App 端
      if (typeof plus !== 'undefined' && typeof plus.runtime !== 'undefined') {
        // App端使用plus.runtime.openURL
        plus.runtime.openURL(urlScheme, () => {
          console.log('打开高德地图成功');
        }, (e) => {
          console.error('打开高德地图失败', e.message);
          // App端失败后提供网页版导航的备选方案
          uni.showModal({
            title: '提示',
            content: '高德地图未安装或无法打开，是否使用网页版导航?',
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url: webUrl
                });
              }
            }
          });
        });
      } else {
        // H5端直接使用window.location.href或uni.navigateTo
        uni.navigateTo({
          url: webUrl
        });
      }
    },
      showWebNavigation(destinationLatitude, destinationLongitude) {
        // 显示网页版导航的toast提示
        this.$refs.toast.show({
          title: '高德地图未安装，将使用网页版导航',
          duration: 2000
        });
        // 跳转到网页版高德地图进行导航
        uni.navigateTo({
          url: `http://uri.amap.com/navigation?to=${destinationLatitude},${destinationLongitude}`
        });
      }
  },
  // 页面加载完成时获取用户位置
  onLoad() {
    this.getCurrentLocation();
	this.fetchShopsData();
  },
  created() {
  	this.getCurrentLocation();
	this.fetchShopsData();
  }
};
</script>


<style scoped>
.page-body {
  display: flex;
  flex-direction: column;
}
.shops-list {
  margin-bottom: 10px;
}
.shop-item {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}
.shop-image {
  width: 50px; /* 根据需要调整 */
  height: 50px; /* 根据需要调整 */
  margin-right: 10px;
}
.shop-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.shop-name {
  font-weight: bold;
}
.shop-address {
  color: #666;
}
.map-container {
  width: 100%;
}
</style>

